package com.cms.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.cms.common.StringUtils;
import com.cms.constant.CmsConstant;
import com.cms.model.TrAdminUser;
import com.cms.model.TrSystemConfig;
import com.cms.service.SystemConfigService;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

@Controller
public class SystemConfigController extends BaseController{
	
	  @Autowired
	  private SystemConfigService configService;

      @RequestMapping("/systemConfig.do")
      public String enter(HttpServletRequest req,HttpServletResponse resp,ModelMap map)throws Exception
      {
    	  List<TrSystemConfig>configs= configService.querySystemConfig();
    	  map.put("systemConfigs", configs);
    	  return "config/systemConfigMain.html";
      }
      
      @RequestMapping("/systemConfig/saveSystemConfig.do")
      public void saveSystemConfig(HttpServletRequest req,HttpServletResponse resp,ModelMap map)throws Exception
      {
    	  String data = req.getParameter("data");
    	  Map<String, Object>result = new HashMap<String, Object>();
    	  if(!StringUtils.isBlank(data))
    	  {
    		    TrAdminUser tu = this.getLoginUser(req);
    		    JsonArray array= new JsonParser().parse(data).getAsJsonArray();
    		    List<TrSystemConfig> configs = new ArrayList<TrSystemConfig>();
    		    TrSystemConfig config=null;
    		    JsonObject obj= null;
    		    for(int i=0;array!=null&&i<array.size();i++)
    		    { 
    		    	obj=array.get(i).getAsJsonObject();
    		    	config =new TrSystemConfig();
    		    	config.setId(obj.get("id").getAsInt());
    		    	config.setName(obj.get("name").getAsString());
    		    	config.setValue(obj.get("value").getAsString());
    		    	config.setModifyUser(tu.getId());
    		    	configs.add(config);
    		    }
    		    if(configs!=null&&!configs.isEmpty())
    		    {
    		    	 this.configService.updateSystemConfig(configs);
    		    	 result.put(CmsConstant.STATUS, CmsConstant.SUCCESS_STATUS);
    		    	 this.renderText(resp, new Gson().toJson(result));
    		    	 return;
    		    }
    	  }  
    	result.put(CmsConstant.STATUS, CmsConstant.FAIL_STATUS);
    	result.put(CmsConstant.MSG, "数据异常，详细信息[“"+data+"”]");
	    this.renderText(resp, new Gson().toJson(result));
      }
}
